#!/bin/sh

# 应用名称
appName=CloudFilter
# 当前路径
currentPath=$(cd `dirname $0`; pwd)
parentPath=`echo $(dirname "${currentPath}")`
# 监控动作文件
actionFile=${currentPath}/cache/.subAction


# 记录日志
addLog(){
	local dtime=`date +'%Y-%m-%d %H:%M:%S'`
	local content="[${dtime}]运行${1}超时重启"
	echo ${content} >> "${currentPath}/logs.txt"
}
# 监控日志
monitorLog(){
	local maxRow=10000
	local logFile="${currentPath}/monitor.log"
	local dtime=`date +'%Y-%m-%d %H:%M:%S'`
	local content="[${dtime}]${1}"
	echo ${content} >> ${logFile}
	local row=`cat ${logFile} | wc -l`
	[[ "${row}" -gt "$(( 2 * maxRow ))" ]] && { sed -i "" "1,$(( row - maxRow ))d" ${logFile}; }
}

# 移动鼠标
moveMouse(){
	local posx=$(($RANDOM%500+1))
	local posy=$(($RANDOM%500+1))
	/usr/bin/python -c "import Quartz.CoreGraphics  as qcg
def mouseMove(posx, posy):
	theEvent = qcg.CGEventCreateMouseEvent(None, qcg.kCGEventMouseMoved, (posx,posy), qcg.kCGMouseButtonLeft);
	qcg.CGEventPost(qcg.kCGHIDEventTap, theEvent);
mouseMove(${posx},${posy});
"
	monitorLog "随机移动鼠标到(${posx},${posy})"
}



# 重启系统
restartOS(){
	# 强制退出Messaegs
	pkill Messages
	# 重启
	sudo shutdown -r now > /dev/null
}

# 重新运行应用
restartApp(){
	# 如果应用已启动则不理会
	if [[ `ps -ef | grep "${appName}" | grep ".app" | grep -v grep | wc -l` -gt 0 ]];then
		/bin/echo -n  > "${actionFile}"
		monitorLog "应用已运行，不用启动"
		exit 0
	fi 
	# 强制退出Messaegs
	pkill Messages
	# 应用必须放在桌面
	local fullAppName=`ls /Users/vmu/Desktop/ | grep "${appName}" | grep ".app"`
	if [[ -n "${fullAppName}" ]]; then
		open "/Users/vmu/Desktop/${fullAppName}"
		sleep 3
		if [[ `ps -ef | grep "${appName}" | grep ".app" | grep -v grep | wc -l` -gt 0 ]];then
			/bin/echo -n  > "${actionFile}"
			monitorLog "启动成功，清空文件"
		fi 
	else
		/bin/echo -n  > "${actionFile}"

		
		monitorLog "应用已被删除，清空文件"
	fi
}


# 随机移动一下鼠标避免屏保
moveMouse

# 控制文件内容
currentAction=""
# 动作名称
subAction=""
# 过期时间
expireTime=""
[[ -f "${actionFile}" ]] && { currentAction=`cat ${actionFile}` ; }

if [[ -n "${currentAction}" ]];then
	subAction=${currentAction%:*}
	expireTime=${currentAction#*:}
fi



#1 如果是重试应用则马上执行
if [[ "${subAction}" = "reRun" ]]; then
	addLog "${subAction}"
	monitorLog "${subAction}应用重启"
	restartApp
	exit 0
fi



#1 如果监控的应用为启动则不做继续
#if [[ `ps -ef | grep "${appName}" | grep ".app" | grep -v grep | wc -l` -eq 0 ]];then
#	monitorLog "应用未启动"
#	exit 0
#fi


# 2 超时处理
runTime=`uptime`
# 包含min即启动时间在1小时内，超过1小时显示格式为HH:MM
[[ "${runTime}" =~ "sec" ]] && { exit 0; }
if [[ "${runTime}" =~ "min" ]];then
	runTimeRight=${runTime#*up}
	runMins=${runTimeRight%min*}
	# 启动超过10分钟
	if [[ "${runMins}" -gt 10 ]];then
		monitorLog "启动运行超过10分钟，30秒后重启"
		sleep  30
		restartOS
		exit 0
	fi
else
	monitorLog "启动运行时间过长，30秒后重启"
	sleep  30
	restartOS
fi
